package cn.livingCloud.controller.content.validator;

import cn.livingCloud.context.Config;
import cn.livingCloud.dto.ImageUploadDto;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by sujiantang on 2015/12/22.
 */
@Component
public class ImageUploadDtoValidator implements Validator {

    public static final Long SIZE_LONG = 0L;

    @Override
    public boolean supports(Class<?> aClass) {
        return ImageUploadDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ImageUploadDto uploadDto = (ImageUploadDto) target;
        validateFile(errors, uploadDto);
    }

    private void validateFile(Errors errors, ImageUploadDto uploadDto) {
        if (SIZE_LONG.equals(uploadDto.getImageFile().getSize())) {
            errors.rejectValue("imageFile", null, "请选择图片");
            return;
        }
        validateSuffix(uploadDto.getImageFile(), errors);
    }

    private void validateSuffix(MultipartFile file, Errors errors) {
        if (!validateExt(file.getOriginalFilename())) {
            errors.rejectValue("imageFile", null, "请上传图片文件");
        }
    }

    /**
     * 验证上传的文件的后缀名是否为图片后缀
     *
     * @param fileName 文件名称
     * @return boolean true/false
     */
    private boolean validateExt(String fileName) {
        String extension = FilenameUtils.getExtension(fileName);
        String[] strings = Config.ALLOW_IMAGE_EXTENSION.split(":");
        for (String item : strings) {
            if (item.equals(extension)) {
                return true;
            }
        }
        return false;
    }
}
